﻿Imports System.Web.UI
Imports System.Collections.Generic
Imports System.Reflection

Imports DotNetNuke
Imports DotNetNuke.Services.Exceptions
Imports DotNetNuke.Services.Localization

Namespace dnnWerk.Modules.Nuntio.Content

    Partial Class Edit
        Inherits ContentBase

#Region "Private Members"

        Private _itemId As Integer = -1

        Private ReadOnly Property ContentCollection() As ContentCollection
            Get
                Dim _content As New ContentCollection
                Try
                    Dim objController As New ContentController
                    _content = objController.ListContent(Me.ModuleId)
                Catch
                End Try
                Return _content
            End Get
        End Property

        Private ReadOnly Property CurrentRole() As String
            Get
                Try
                    Return ucOptions.SelectedRole
                Catch
                End Try
                Return "GENERIC"
            End Get
        End Property

#End Region

#Region "Event Handlers"

        Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
            DotNetNuke.Framework.AJAX.RegisterScriptManager()            
            BindTabs()
            BindEditors()
            RegisterScripts()
        End Sub

        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

            Try

                ucOptions.ModuleId = ModuleId

                If Not Page.IsPostBack Then

                    BindFallbackLocales(drpFallbackLocale)

                    If DefaultFallback <> "NONE" Then
                        Try
                            drpFallbackLocale.SelectedValue = DefaultFallback
                        Catch
                            'fallback locale doesn't exist anymore
                        End Try
                    End If

                    'currentRole = "GENERIC"
                    'strCurrentRole = Localization.GetString("lblGeneric.Text", Me.LocalResourceFile)

                    BindData(ucOptions.SelectedRole)

                End If

                LocalizeForm()

            Catch exc As Exception        'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try

        End Sub

        Private Sub cmdUpdateExit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdUpdateExit.Click

            Update(True)

        End Sub

        Private Sub cmdUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdUpdate.Click

            Update(False)

        End Sub

        Private Sub cmdDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdDelete.Click

        End Sub

        Private Sub cmdCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdCancel.Click

            Response.Redirect(NavigateURL(), True)

        End Sub

        Private Sub PreferencesUpdated(ByVal sender As Object, ByVal e As System.EventArgs) Handles ucPreferences.PreferencesUpdated

            Response.Redirect(Me.Request.RawUrl, True)

        End Sub

        Private Sub Content_Loaded(ByVal sender As Object, ByVal e As ContentChangedEventArgs)
            BindData(Me.CurrentRole, e.Locale, e.NewVersion)
        End Sub

        Private Sub Content_Deleted(ByVal sender As Object, ByVal e As ContentChangedEventArgs)
            Dim ctl As New ContentController
            ctl.DeleteContent(e.ContentId)
            BindData(Me.CurrentRole, e.Locale, Null.NullInteger)
        End Sub

        Private Sub Role_Changed(ByVal sender As Object, ByVal e As RoleChangedEventArgs) Handles ucOptions.ContentChanged, ucOptions.RoleChanged

            Dim i As Integer
            Dim info As System.Globalization.CultureInfo

            For i = 0 To SupportedLocales.Count - 1

                info = System.Globalization.CultureInfo.CreateSpecificCulture(CType(SupportedLocales(i).Value, Locale).Code)

                SelectTab(0)

                If info.Name.ToLower = CurrentLocale.ToLower Then
                    SelectTab(i)
                End If

            Next

            BindData(e.RoleName)

        End Sub

#End Region

#Region "Private Methods"

        Private Sub BindData(ByVal strRole As String)
            BindData(strRole, Null.NullString, Null.NullInteger)
        End Sub

        Private Sub BindData(ByVal strRole As String, ByVal strLocale As String, ByVal Version As Integer)

            If ContentCollection.Count > 0 Then
                For Each ctl As Control In plhEditors.Controls
                    If TypeOf (ctl) Is uc_Editor Then
                        Dim editor As uc_Editor = CType(ctl, uc_Editor)

                        If (editor.Locale = strLocale) Or strLocale = Null.NullString Then

                            If Not editor Is Nothing Then

                                editor.DataBind()

                                Dim content As ContentInfo = ContentCollection.FindItem(editor.Locale, strRole, Version)

                                If Not content Is Nothing Then

                                    Dim blnFallbackFound As Boolean = False
                                    If content.IsFallback Then
                                        blnFallbackFound = True
                                        drpFallbackLocale.SelectedValue = content.Locale
                                    Else
                                        For Each checkContent As ContentInfo In ContentCollection.Items
                                            If checkContent.Locale.ToLower <> content.Locale.ToLower Then
                                                If checkContent.Role.ToLower = content.Role.ToLower Then
                                                    If checkContent.IsFallback Then
                                                        blnFallbackFound = True
                                                        drpFallbackLocale.SelectedValue = checkContent.Locale
                                                    End If
                                                End If
                                            End If
                                        Next
                                    End If
                                    If blnFallbackFound = False Then
                                        drpFallbackLocale.SelectedValue = "-1"
                                    End If

                                    If content.Content = "" Then
                                        editor.Content = "Enter content for " & CurrentRole
                                    Else
                                        Dim processor As New ContentProcessor(Server.HtmlDecode(content.Content), "editorpreview", Me.LocalResourceFile, Me.TemplateSourceDirectory, Me.PortalSettings, ModuleId, Settings)
                                        processor.Process()
                                        editor.Content = processor.ParsedContent
                                    End If

                                    editor.Role = strRole

                                    editor.Title = content.Title
                                    'try loading module title from previous module versions
                                    If Not Settings("PNC_CONTENT_MODULETITLE_" & editor.LCID) Is Nothing Then
                                        editor.Title = CType(Settings("PNC_CONTENT_MODULETITLE_" & editor.LCID), String)
                                    End If

                                    editor.IsPublished = content.IsPublished
                                    editor.Version = content.Version

                                Else

                                    'try to set title to original entry
                                    Try
                                        For Each oContent As ContentInfo In ContentCollection.Items
                                            If oContent.Locale.ToLower = editor.Locale.ToLower Then
                                                editor.Title = oContent.Title
                                            End If
                                        Next
                                    Catch
                                    End Try

                                    editor.IsPublished = False
                                    editor.Role = strRole
                                    editor.Version = 1

                                End If

                                editor.BindControl()


                            End If

                        End If
                        
                    End If
                Next
            End If

        End Sub

        Private Sub FixFCKAjax(ByVal TextEditorType As Type)

            If DotNetNuke.Framework.AJAX.IsInstalled() Then
                If TextEditorType.FullName.ToLower.Contains("fckhtmleditorprovider") Then
                    Dim sm As ScriptManager = ScriptManager.GetCurrent(Me.Page)
                    If Not sm Is Nothing Then
                        Dim strScript As String = "for ( var i = 0; i < parent.frames.length; ++i ) if ( parent.frames[i].FCK ) parent.frames[i].FCK.UpdateLinkedField();"
                        ScriptManager.RegisterOnSubmitStatement(Me.Page, Me.GetType(), "FCKAjaxHack", strScript)
                    End If
                End If
            End If

        End Sub

        Private Sub Update(ByVal blnExit As Boolean)

            'update content of current texteditors
            Dim objContentController As New ContentController

            Try

                'find all texteditor controls                
                Dim strLastAction As String = ""
                Dim intPriority As Integer = ContentCollection.GetNextPriority(CurrentRole)
                

                Dim strLocale As String = CurrentLocale
                Dim strRole As String = CurrentRole

                'loop through each texteditor instance and update content

                For Each ctl As Control In plhEditors.Controls
                    If TypeOf (ctl) Is uc_Editor Then

                        Dim blnContentChanged As Boolean
                        Dim blnPropertiesChanged As Boolean
                        Dim blnNewContent As Boolean = False
                        Dim blnNeedToPersist As Boolean = False

                        Dim editor As uc_Editor = CType(ctl, uc_Editor)
                        strLocale = editor.Locale


                        'remove old module title setting for older versions                        
                        Dim mc As New Entities.Modules.ModuleController
                        mc.DeleteModuleSetting(ModuleId, "PNC_CONTENT_MODULETITLE_" & editor.LCID)

                        Dim intVersion As Integer = 1
                        Dim objCheck As ContentInfo = ContentCollection.FindItem(strLocale, CurrentRole)
                        If Not objCheck Is Nothing Then

                            'content found, we're in update mode  

                            editor.MatchContent(objCheck, blnContentChanged, blnPropertiesChanged)

                            If objCheck.IsFallback Then
                                If drpFallbackLocale.SelectedValue.ToLower <> objCheck.Locale.ToLower Then
                                    'fallback changed
                                    blnPropertiesChanged = True
                                End If
                            Else
                                If drpFallbackLocale.SelectedValue.ToLower = objCheck.Locale.ToLower Then
                                    'fallback changed
                                    blnPropertiesChanged = True
                                End If
                            End If

                            blnNeedToPersist = (blnContentChanged Or blnPropertiesChanged)

                            If blnContentChanged Then
                                intVersion = ContentCollection.GetNextVersion(CurrentRole, strLocale)
                            End If

                        Else

                            blnNewContent = True
                            blnNeedToPersist = IsContent(Server.HtmlDecode(editor.SelectedContent))

                        End If

                        If blnNeedToPersist Then

                            'something has changed, persist changes to db
                            Dim objContent As ContentInfo = Nothing

                            If blnNewContent Then

                                objContent = New ContentInfo
                                objContent.CreatedBy = Me.UserId
                                objContent.CreatedDate = Date.Now

                            Else

                                objContent = objCheck

                            End If

                            objContent.ModuleId = Me.ModuleId
                            objContent.Locale = editor.Locale
                            objContent.Role = CurrentRole
                            objContent.IsPublished = editor.ContentIsVisible

                            If drpFallbackLocale.SelectedValue.ToLower = editor.Locale.ToLower Then
                                objContent.IsFallback = True
                            Else
                                objContent.IsFallback = False
                            End If

                            objContent.Version = intVersion

                            'process content of new object
                            Dim objContentProcessor As New ContentProcessor(Server.HtmlDecode(editor.SelectedContent), "updatedb", Me.LocalResourceFile, Me.TemplateSourceDirectory, Me.PortalSettings, ModuleId, Settings)
                            objContentProcessor.Process()
                            objContent.Content = objContentProcessor.ParsedContent

                            objContent.Title = editor.SelectedTitle
                            objContent.Priority = intPriority

                            If blnNewContent Then

                                'add content    
                                objContent.ContentId = objContentController.AddContent(objContent)
                                strLastAction = "add"

                            Else

                                If (blnContentChanged = True) Then

                                    'content changed, add new version
                                    objContent.CreatedBy = UserInfo.UserID
                                    objContent.CreatedDate = Date.Now
                                    objContent.ContentId = objContentController.AddContent(objContent, UserId, editor.SelectedComment)
                                    strLastAction = "addversion"

                                Else

                                    'no content changes
                                    If blnPropertiesChanged Then

                                        'properties changed, update last version
                                        objContentController.UpdateContent(objContent, UserInfo.UserID, editor.SelectedComment, True)
                                        strLastAction = "update"

                                    End If

                                End If

                            End If

                            'If objContent.IsPublished Then
                            '    'make sure all other content is set to hidden
                            '    For Each otherContent As ContentInfo In ContentCollection.Items
                            '        If otherContent.Locale = editor.Locale AndAlso otherContent.Role.ToLower = CurrentRole.ToLower Then
                            '            'don't change current object
                            '            If Not otherContent.ContentId = objContent.ContentId Then
                            '                otherContent.IsPublished = False
                            '                objContentController.UpdateContent(otherContent, otherContent.CreatedBy, "", False)
                            '            End If
                            '        End If
                            '    Next                            
                            'End If


                            For Each otherContent As ContentInfo In ContentCollection.Items
                                If otherContent.Role.ToLower = CurrentRole.ToLower Then
                                    If otherContent.Locale.ToLower = drpFallbackLocale.SelectedValue.ToLower Then
                                        otherContent.IsFallback = True
                                    Else
                                        otherContent.IsFallback = False
                                    End If

                                    If objContent.IsPublished Then
                                        If otherContent.Locale = editor.Locale AndAlso otherContent.Role.ToLower = CurrentRole.ToLower Then
                                            'don't change current object
                                            If Not otherContent.ContentId = objContent.ContentId Then
                                                otherContent.IsPublished = False
                                            End If
                                        End If
                                    End If

                                    objContentController.UpdateContent(otherContent, otherContent.CreatedBy, "", False)
                                End If
                            Next

                           

                            

                        End If

                    End If

                Next

                If blnExit Then
                    'back to page   
                    Response.Redirect(NavigateURL(), True)
                Else
                    'set status message
                    Select Case strLastAction
                        Case "update"
                            'SetMessage(String.Format(Localization.GetString("ContentUpdated.Text", Me.LocalResourceFile), GetRoleName(_currentEditorRole)), True)
                        Case "add"
                            'SetMessage(String.Format(Localization.GetString("ContentSaved.Text", Me.LocalResourceFile), GetRoleName(_currentEditorRole)), True)
                        Case "addversion"
                            'SetMessage(String.Format(Localization.GetString("VersionAdded.Text", Me.LocalResourceFile), GetRoleName(_currentEditorRole)), True)
                    End Select
                End If
              
            Catch ex As Exception

            End Try


        End Sub

        Private Function IsContent(ByVal strContent As String) As Boolean
            If strContent = "<p>&nbsp;</p>" Then
                Return False
            End If
            If strContent = "<p>&#160;</p>" Then
                Return False
            End If
            If strContent = "<div>&nbsp;</div>" Then
                Return False
            End If
            If strContent = "<div>&#160;</div>" Then
                Return False
            End If
            If strContent = "" Or strContent = " " Then
                Return False
            End If
            If strContent = "<br />" Then
                Return False
            End If
            Return True
        End Function

        Private Sub RegisterScripts()

            UIHelper.InjectjQueryLibary(Me.Page, True, False, True)
            UIHelper.IncludeCSSFile(Me.Page, "Nuntio-Content-jQueryUI", Me.ResolveUrl("~/Desktopmodules/Nuntio.Content/scripts/css/ui-lightness/jquery-ui-1.8.custom.css"))
            UIHelper.IncludeCSSFile(Me.Page, "Nuntio-Content-UIStyles", ResolveUrl("~/Desktopmodules/Nuntio.Content/css/edit.css"))
            UIHelper.IncludeScriptFile(Me.Page, "Nuntio-Content-Custom", ResolveUrl("~/Desktopmodules/Nuntio.Content/scripts/js/Nuntio.Content.js"))

            'Dim strjQuery As String = "<script type=""text/javascript"" src=""" & Me.ResolveUrl("~/Desktopmodules/Nuntio.Content/scripts/js/jquery-1.4.2.min.js") & """></script>"
            'Try
            '    Me.Page.FindControl("Head").Controls.Add(New LiteralControl(strjQuery))
            'Catch
            'End Try

            'Dim strjQueryUI As String = "<script type=""text/javascript"" src=""" & Me.ResolveUrl("~/Desktopmodules/Nuntio.Content/scripts/js/jquery-ui-1.8.custom.min.js") & """></script>"
            'Try
            '    Me.Page.FindControl("Head").Controls.Add(New LiteralControl(strjQueryUI))
            'Catch
            'End Try

            'Dim strUICss As String = "<link href=""" & Me.ResolveUrl("~/Desktopmodules/Nuntio.Content/scripts/css/ui-lightness/jquery-ui-1.8.custom.css") & """ rel=""stylesheet"" type=""text/css"" />"
            'Try
            '    Me.Page.FindControl("CSS").Controls.Add(New LiteralControl(strUICss))
            'Catch
            'End Try

            'Dim strEditCss As String = "<link href=""" & Me.ResolveUrl("~/Desktopmodules/Nuntio.Content/css/edit.css") & """ rel=""stylesheet"" type=""text/css"" />"
            'Try
            '    Me.Page.FindControl("CSS").Controls.Add(New LiteralControl(strEditCss))
            'Catch
            'End Try

            ''Dim strScript As String = ""            
            ''strScript += "jQuery(document).ready(function() {" & vbNewLine
            ''strScript += "  jQuery("".ncTbSt"").tabs();" & vbNewLine
            ''strScript += "});" & vbNewLine

            ''Me.Page.ClientScript.RegisterClientScriptBlock(Me.GetType, "ncTabs", strScript, True)

        End Sub

        Private Sub LocalizeForm()

            Me.lblModuleFallback.Text = Localization.GetString("lblModuleFallback", Me.LocalResourceFile)
            Me.drpFallbackLocale.Items(0).Text = Localization.GetString("NoFallback", Me.LocalResourceFile)
            Me.lblCancelButton.Text = Localization.GetString("cmdCancel", Me.LocalResourceFile)
            Me.lblDeleteButton.Text = Localization.GetString("cmdDelete", Me.LocalResourceFile)
            Me.lblUpdateButton.Text = Localization.GetString("cmdUpdate", Me.LocalResourceFile)

        End Sub

        Private Sub BindTabs()

            Dim i As Integer
            Dim info As System.Globalization.CultureInfo

            For i = 0 To SupportedLocales.Count - 1

                info = System.Globalization.CultureInfo.CreateSpecificCulture(CType(SupportedLocales(i).Value, Locale).Code)

                Dim ctlTab As uc_Tab = CType(LoadControl(ResolveUrl("~" & Me.ModuleDirectory & "controls/uc_Tab.ascx")), uc_Tab)
                ctlTab.TabText = GetLocaleDisplay(info)
                ctlTab.Identifier = info.Name
                plhTabs.Controls.Add(ctlTab)

                SelectTab(0)

                If Not Page.IsPostBack Then
                    If info.Name.ToLower = CurrentLocale.ToLower Then
                        SelectTab(i)
                    End If
                End If

            Next

            'add settings tab
            Dim ctlPreferencesTab As uc_Tab = CType(LoadControl(ResolveUrl("~" & Me.ModuleDirectory & "controls/uc_Tab.ascx")), uc_Tab)
            ctlPreferencesTab.TabText = "<img src=""" & Me.ModuleDirectory & "images/tab_settings.png"" alt=""Preferences"" />Preferences"
            ctlPreferencesTab.Identifier = "nc_Preferences"
            plhTabs.Controls.Add(ctlPreferencesTab)

            'add advanced tab
            Dim ctlOptionsTab As uc_Tab = CType(LoadControl(ResolveUrl("~" & Me.ModuleDirectory & "controls/uc_Tab.ascx")), uc_Tab)
            ctlOptionsTab.TabText = "<img src=""" & Me.ModuleDirectory & "images/tab_settings.png"" alt=""Options"" />Optionen"
            ctlOptionsTab.Identifier = "nc_Options"
            plhTabs.Controls.Add(ctlOptionsTab)

        End Sub

        Private Sub SelectTab(ByVal index As Integer)
            Me.txtSelectedTab.Text = index.ToString
        End Sub

        Private Sub BindEditors()

            Dim i As Integer
            Dim info As System.Globalization.CultureInfo

            For i = 0 To SupportedLocales.Count - 1

                info = System.Globalization.CultureInfo.CreateSpecificCulture(CType(SupportedLocales(i).Value, Locale).Code)

                plhEditors.Controls.Add(New LiteralControl("<div id=""tab_" & info.Name & """>"))
                Dim ctlEditor As uc_Editor = CType(LoadControl(ResolveUrl("~" & Me.ModuleDirectory & "controls/uc_Editor.ascx")), uc_Editor)
                ctlEditor.Locale = info.Name
                ctlEditor.Role = CurrentRole
                ctlEditor.ModuleId = ModuleId
                ctlEditor.LCID = info.LCID
                ctlEditor.Version = 1

                AddHandler ctlEditor.ContentDeleted, AddressOf Content_Deleted
                AddHandler ctlEditor.ContentLoaded, AddressOf Content_Loaded

                plhEditors.Controls.Add(ctlEditor)
                plhEditors.Controls.Add(New LiteralControl("</div>"))

            Next

        End Sub

#End Region

    End Class

End Namespace
